<?php
/**
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_1
 * @license    GNU/GPL
 * TODO
 * datetime not working
*/
 
// I must send post not share on this batchupload ... 
 
// no direct access
 
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.filesystem.path' );
jimport( 'joomla.application.component.view');
jimport( 'joomla.database.database' );





 
// Create a new query object.
//$query = $db->getQuery(true);
 
// Insert columns.
//$columns = array('user_id', 'profile_key', 'profile_value', 'ordering');
 
// Insert values.
//$values = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
 
// Prepare the insert query.
//$query
//    ->insert($db->quoteName('#__user_profiles'))
//    ->columns($db->quoteName($columns))
//    ->values(implode(',', $values));
 
// Reset the query using our newly populated query object.
//$db->setQuery($query);


/**
 * HTML View class for the HelloWorld Component
 *
 * @package    HelloWorld
 */
class wotclanViewbatchupload extends JView
{
    function display($tpl = null)
    {
    	if (JFactory::getUser()->authorise('core.add', 'com_helloworld')) 
      {
		jimport('joomla.filesystem.file');
        $db =& JFactory::getDbo();
        $greeting = "Uploader votre replay! (V0.0.1)";
        $this->assignRef( 'greeting', $greeting );
        
        // get user info
        
    	$user =& JFactory::getUser();
		$usr_id = $user->get('id');
				
        $repuniq=uniqid("", true);
		$rep="media/wotclan/replays/".$repuniq;
		mkdir($rep);
         //Retrieve file details from uploaded file, sent from upload form
		$file = JRequest::getVar('file_upload', null, 'files', 'array');
 
				//Import filesystem libraries. Perhaps not necessary, but does not hurt
 
				//Clean up filename to get rid of strange characters like spaces etc
		$filename = JFile::makeSafe($file['name']);
        parent::display($tpl);
        if ($_FILES["file"]["error"] > 0)
  			{
  				echo "Error: " . $_FILES["file"]["error"] . "<br>";
  			}
				//else
  			//{
  			//	echo "Upload: " . $_FILES["file_upload"]["name"] . "<br>";
  			//	echo "Type: " . $_FILES["file_upload"]["type"] . "<br>";
  			//	echo "Size: " . ($_FILES["file_upload"]["size"] / 1024) . " kB<br>";
  			//	echo "Stored in: " ."media/wotclan/replays/" . $_FILES["file"]["name"]  ;
 
  			//}

 
				//Set up the source and destination of the file
				// $src = $file['tmp_name'];
				$src = $_FILES["file_upload"]['tmp_name'];
				$dest = JPATH_ROOT.DS. "media" . DS . "wotclan" . DS . "replays" . DS . $repuniq . DS . $_FILES["file_upload"]["name"];
 				//echo "<br>new dest : " . $dest ;

 
				//First check if the file has the right extension, we need jpg only
			if ( strtolower(JFile::getExt($filename) ) == 'zip') {
   			if ( JFile::upload($src, $dest) ) {
   		    	$zip = new ZipArchive;
                $res = $zip->open($dest);
                if ($res === TRUE) {
  					$zip->extractTo(JPATH_ROOT.DS. "media" . DS . "wotclan" . DS . "replays" . DS . $repuniq . DS);
  					for($i = 0; $i < $zip->numFiles; $i++) {
                    $filename = $zip->getNameIndex($i);
                    //echo "<h1>".$filename."</h1><br>";
                    $fp = fopen(JPATH_ROOT.DS. "media" . DS . "wotclan" . DS . "replays" . DS . $repuniq . DS . $filename , 'rb');
                    while ( ($line = fgets($fp)) !== false) {
    				    if ((preg_match("/mapName/i", $line)) || (preg_match("/frags/i", $line))){
    					    
    					    $keywords = preg_split("/,/", $line);
    						$x=0;
    					    while ($keywords[$x] !== '' && $x < 300) {
    						    if (preg_match("/mapName/i", $keywords[$x])){
    							    $mapname=preg_replace('/.*"mapName": "(.*)"/','$1',$keywords[$x]);
    							    $mapname=preg_replace('/\s/','',$mapname);
    							    //echo "<br>here the map : " . $mapname . "<br>";
    						    }
    						    if (preg_match("/playerID/i", $keywords[$x])){
    							    $playerid=preg_replace('/"playerID": (.*)/','$1',$keywords[$x]);
    							    $playerid=preg_replace('/\s/','',$playerid);
    							    //echo "<br>here the PlayerID : " . $playerid . "<br>";
    							
    				
    						    }
    						    if (preg_match("/playerVehicle/i", $keywords[$x])){
    							    $playerVehicle=preg_replace('/"playerVehicle": "(.*)"/','$1',$keywords[$x]);
    							    $playerVehicle=preg_replace('/\s/','',$playerVehicle);
    							    //echo "<br>here the playerVehicle : " . $playerVehicle . "<br>";
    						    }
    						    if (preg_match("/gameplayID/i", $keywords[$x])){
    							    $gameplayID=preg_replace('/"gameplayID": "(.*)"/','$1',$keywords[$x]);
    							    $gameplayID=preg_replace('/\s/','',$gameplayID);
    							    //echo "<br>here the gameplayID : " . $gameplayID . "<br>";
    						    }
    						    if (preg_match("/playerName/i", $keywords[$x])){
    							    $playerName=preg_replace('/"playerName": "(.*)"/','$1',$keywords[$x]);
    							    $playerName=preg_replace('/\s/','',$playerName);
    							    //echo "<br>here the playerName : " . $playerName . "<br>";


                                    $query = $db->getQuery(true);
                  // Select all records from the user profile table where key begins with "custom.".
                  // Order it by the ordering field.
                                    $query="SELECT * FROM `#__wotclan_account` WHERE name='".$playerName."'";
                  //$query=->select(array('name', 'clan', 'uniqid'));
                  //$query->from('#__wotclanplayers');
                  //$query->where('name LIKE \''. $playerName . '\'');
                  //$query->order('ordering ASC');
 									//echo "<br>QUERY : ".$query."<br>";
                  // Reset the query using our newly populated query object.
                                    $db->setQuery($query);
                                    $db->query(); 

                  // Load the results as a list of stdClass objects.
                  //$results = $db->loadObjectList();
                                    $num_rows = $db->getNumRows();
									if($num_rows>1){
										echo "Prob with ".$playerName." on db, mor then one result";
									}	elseif ($num_rows>0) {
									
										$rows = $db->loadObjectList();
  									foreach ( $rows as $row ) {
    									$uniqaccount=$row->uniqid;
    									
  									}
										//echo "<br>".$playerName." already exist in DB<br>";
										
 									} else {
           //       if ($results['column'] == NULL) { 
                  	//echo "<br>No result = " .$results."<br>";
                    
                                        $db =& JFactory::getDBO();
										$uniqaccount=uniqid("", true);
    								
										$query2 = "INSERT INTO `#__wotclan_account` (`id`,`uniqid`, `name`,`playerid`,`uid`)
										VALUES (NULL,'".$uniqaccount."',  '".$playerName."','".$playerid."','".$usr_id."');";
    								//echo "<br>".$query2."<br>";
										$db->setQuery( $query2 );
										$db->query();   
                  
                  	
                                    }
                  // verify if user is on user DB
								$query = $db->getQuery(true);
        					    $query="SELECT * FROM `#__wotclan_user` WHERE uid='".$usr_id."'";
        					    $db->setQuery($query);
        					    $db->query();
        					    $num_rows = $db->getNumRows();
								if($num_rows>1){
								    echo "Prob with ".$usr_id." on db, more then one result";
								}	elseif ($num_rows>0) {
								    $rows = $db->loadObjectList();
  									foreach ( $rows as $row ) {
    								  //	verify if account is on user db
    								  if (preg_match("/".$uniqaccount."/",$row->account)){
    								  	echo "Account already present";
    								  } else {
    								  	echo "Adding account to db";
    								  	if ($row->account == "") {
    								  		$newaccount=$uniqaccount;
    								  	} else {
    								  		$newaccount=$row->account."|".$uniqaccount;
    								  	}
    								  	$query2 = $db->getQuery(true);
    								  	$query2="UPDATE `#__wotclan_user` SET `account`='".$newaccount."' WHERE uid='".$usr_id."';";
    								  	$db->setQuery($query2);
        								$db->query();													    								  	
    								  }
  									}
        					    } else { 
        						
        						$query2 = $db->getQuery(true);
        						$query2 = "INSERT INTO `#__wotclan_user` (`id`,`uniqid`, `uid`,`account`)
    										VALUES (NULL,'".uniqid("", true)."',  '".$usr_id."','".$uniqaccount."');";
    							$db->setQuery($query2);
        						$db->query();
    										
        					    } 
    						}    		
    						if (preg_match('/"vehicles": {/i', $keywords[$x])){	
    							$y=0;
    							$t1=0;
    							$t2=0;
    			  			    while ($y < 30){
    				  			    $vehicleType[$y]=preg_replace('/.*"vehicleType": "(.*)"/','$1',$keywords[$x+($y*7)]);
    				  			    $vehicleType[$y]=preg_replace('/\s/','',$vehicleType[$y]);
    				  			    $isAlive[$y]=preg_replace('/"isAlive": (.*)/','$1',$keywords[$x+1+($y*7)]);
    				  			    $isAlive[$y]=preg_replace('/\s/','',$isAlive[$y]);
    				  			    $name[$y]=preg_replace('/"name": "(.*)"/','$1',$keywords[$x+2+($y*7)]);
    				  			    $name[$y]=preg_replace('/\s/','',$name[$y]);
    				  			    $clanAbbrev[$y]=preg_replace('/"clanAbbrev": "(.*)"/','$1',$keywords[$x+3+($y*7)]);
    				  			    $clanAbbrev[$y]=preg_replace('/\s/','',$clanAbbrev[$y]);
    				  			    $team[$y]=preg_replace('/"team": (?)/','$1',$keywords[$x+4+($y*7)]);
    				  			    $team[$y]=preg_replace('/\s/','',$team[$y]);
    				  			    $event[$y]=preg_replace('/"events": {(.*)}/','$1',$keywords[$x+5+($y*7)]);
    				  			    $event[$y]=preg_replace('/\s/','',$event[$y]);
    				  			    $isTeamKiller[$y]=preg_replace('/"isTeamKiller": (true|false).*/','$1',$keywords[$x+6+($y*7)]);
    				  			    $isTeamKiller[$y]=preg_replace('/\s/','',$isTeamKiller[$y]);
    				  			//echo "<br>vehicleType of player " . $y . " : " . $vehicleType[$y] . "<br>";
    				  			//echo "<br>isAlive of player " . $y . " : " . $isAlive[$y] . "<br>";
    				  			//echo "<br>name of player " . $y . " : " . $name[$y] . "<br>";
    				 				//echo "<br>clanAbbrev of player " . $y . " : " . $clanAbbrev[$y] . "<br>";
    				  			//echo "<br>team of player " . $y . " : " . $team[$y] . "<br>";
    				  			
    				  			// steam1 et sttankt1 steing pour la db bataille
    				  			    if ($team[$y]==1){
    				  				    $team1[$t1]=$y;
    				  				    if ($steam1 == ""){
    				  					    $steam1=$name[$y];
    				  					    $sttankt1=$vehicleType[$y];
    				  				    } else {
    				  					    $steam1=$steam1."|".$name[$y];
    				  					    $sttankt1=$sttankt1."|".$vehicleType[$y];
    				  				    }
    				  				$t1++;	
    				  			    } else {
    				  				    $team2[$t2]=$y;
    				  				
    				  				    if ($steam2 == ""){
    				  					    $steam2=$name[$y];
    				  					    $sttankt2=$vehicleType[$y];
    				  					
    				  				    } else {
    				  					    $steam2=$steam2."|".$name[$y];
    				  					    $sttankt2=$sttankt2."|".$vehicleType[$y];
    				  				    }
    				  				    $t2++;	
    				  			    }
    				  			//echo "<br>event of player " . $y . " : " . $event[$y] . "<br>";
    				  			//echo "<br>isTeamKiller of player " . $y . " : " . $isTeamKiller[$y] . "<br>";
    				  			//la partie pour le tank
    				  			    $query = $db->getQuery(true);
                  	                $query="SELECT * FROM `#__wotclan_tanks` WHERE name='".$vehicleType[$y]."'";
                  	//echo "<br>QUERY : ".$query."<br>";
                  	                $db->setQuery($query);
                  	                $db->query();
                  	                $num_rows = $db->getNumRows();
                  	                $rows = $db->loadObjectList();
                  	                foreach ( $rows as $row ) {
    										//echo "<br>test : ".$row->name."<br>";
  									}
									if($num_rows>1){
									    echo "<br><h1>Il y a un probleme avec le vehicule  ".$vehicleType[$y].": il y a plus d'un resultat</h1><br>";
										$rows = $db->loadObjectList();
  										foreach ( $rows as $row ) {
    										echo "<br>test : ".$row->name."<br>";
  										}
									} elseif ($num_rows>0){
									    //echo "<br>Vehicule  ".$vehicleType[$y]." deja present <br>";
											//$db =& JFactory::getDBO();
											//$query2 = "SELECT * FROM `#__wotclantanks` WHERE name='".$vehicleType[$y]."'";
											//$db->setQuery($query2);
                  		//$db->query();
										$tankuniq=$row->uniqid;
											
										} else {
  										    $db =& JFactory::getDBO();
  										    $tankuniq=uniqid("", true);
										    $query2 = "INSERT INTO `#__wotclan_tanks` (`id`,`uniqid`, `name`)
    									VALUES (NULL,'".$tankuniq."',  '".$vehicleType[$y]."');";
    									//echo "<br>".$query2."<br>";
											$db->setQuery( $query2 );
											$db->query();   
  									}
    				  			// La partie pour le joueur
    				  			$query = $db->getQuery(true);
                  	$query="SELECT * FROM `#__wotclan_account` WHERE name LIKE '".$name[$y]."'";
                  	//echo "<br>QUERY : ".$query."<br>";
                  	$db->setQuery($query);
                  	$db->query(); 

                  	$num_rows = $db->getNumRows();
                  	$rows = $db->loadObjectList();
                  	foreach ( $rows as $row ) {
    											echo "<br>"; //test : ".$row->name.": ".$row->uid."<br>";
  											}
										if($num_rows>1){
											echo "<br><h1>Il y a un probleme avec le joueur ".$name[$y].": il y a plus d'un resultat</h1><br>";
											
  											foreach ( $rows as $row ) {
    											echo "<br>test : ".$row->name.": ".$row->uid."<br>";
  											}
										} elseif ($num_rows>0){
												
											echo "<br>Joueur ".$name[$y]." deja present <br>";
												// verifier si il a le bon clan 
											if ($row->clan != $clanAbbrev[$y]){
										    	//echo "<br>Le joueur ".$name[$y]." a changer de clan<br>";
												//echo "<br> rows->clan :".$row->clan."<br>clanabb : ". $clanAbbrev[$y]."<br>";
												$query2 = $db->getQuery(true);
												$query2="UPDATE `#__wotclan_account` SET `clan`='".$clanAbbrev[$y]."' WHERE name='".$name[$y]."';";
												$db->setQuery($query2);
                  				                $db->query(); 
													
											}
												// et le tank
												// donc savoir si le uid du tank ($tankuniq) est dans $query->tanks;
											if (preg_match("/".$tankuniq."/", $row->tanks)){
												echo "<br>";//Le tank ".$vehicleType[$y]."(".$tankuniq.") du joueur ".$name[$y]." est deja present dans la DB<br>";
											} else {
													// ajouter le tank 
												//echo "<br>Le tank ".$vehicleType[$y]."(".$tankuniq.") du joueur ".$name[$y]." n est pas present dans la DB<br>";
												if ($row->tanks == NULL){
													$SEP="";
												} else {
													$SEP="|";
												}
												$stringvehicule=$row->tanks.$SEP.$tankuniq;
												//echo "<br>new string pour vehicule : ".$stringvehicule."<br>";
												$query2 = $db->getQuery(true);
												$query2="UPDATE `#__wotclan_account` SET `tanks`='".$stringvehicule."' WHERE name='".$name[$y]."';";
												//echo "<br>Query for uupdate vehicule : ".$query2."<br>";
												$db->setQuery($query2);
                  				                $db->query();
											}
												
												
										} else {
  											$db =& JFactory::getDBO();
												$query2 = "INSERT INTO `#__wotclan_account` (`id`,`uniqid`, `name`,`clan`,`tanks`)
    										VALUES (NULL,'".uniqid("", true)."',  '".$name[$y]."','".$clanAbbrev[$y]."','".$tankuniq."');";
    										//echo "<br>".$query2."<br>";
												$db->setQuery( $query2 );
												$db->query();   
  										}
    				  			$y++;
    							}
    				
    				
    						}
    						if (preg_match('/"mapDisplayName"/i', $keywords[$x])){	
    							$mapDisplayName=preg_replace('/"mapDisplayName": "(.*)"/','$1',$keywords[$x]);
    			 				//echo "<br>mapDisplayName : " . $mapDisplayName . "<br>";
    			 				$query = $db->getQuery(true);
                                $query="SELECT * FROM `#__wotclan_maps` WHERE name='".$mapDisplayName."'";
                  	//echo "<br>QUERY : ".$query."<br>";
                  	            $db->setQuery($query);
                  	            $db->query();
                  	            $num_rows = $db->getNumRows();
								if($num_rows>1){
								    echo "<br><h1>Il y a un probleme avec la map ".$mapDisplayName.": il y a plus d'un resultat</h1><br>";
									$rows = $db->loadObjectList();
  									foreach ( $rows as $row ) {
    										echo "<br>";//test : ".$row->name."<br>";
  									}
								} elseif ($num_rows>0){
								    //echo "<br>Map  ".$mapDisplayName." deja present <br>";
									if ($mapname != $rows->wotname){
										$query2 = $db->getQuery(true);
										$query2="UPDATE `#__wotclanmaps` SET `wotname`='".$mapname."' WHERE name='".$mapDisplayName."';";
										//echo "query for changing wotname map : ".$query2;
										$db->setQuery($query2);
                  			            $db->query();
									}
											//$db =& JFactory::getDBO();
											//$query2 = "SELECT * FROM `#__wotclantanks` WHERE name='".$vehicleType[$y]."'";
											//$db->setQuery($query2);
                  		//$db->query();
											
											
								} else {
  									$db =& JFactory::getDBO();
  									$mapuniq=uniqid("", true);
									$query2 = "INSERT INTO `#__wotclan_maps` (`id`,`uniqid`, `name`,`wotname`)
    								VALUES (NULL,'".$mapuniq."',  '".$mapDisplayName."','".$mapname."');";
    								//echo "<br>".$query2."<br>";
									$db->setQuery( $query2 );
									$db->query();   
  								}
    						}    		
    						if (preg_match('/dateTime/i', $keywords[$x])){
    			  			$test=preg_match('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).* (\d{2}):(\d{2}):(\d{2}).*"}/',$keywords[$x],$matches);
    			  			//$mm=preg_replace('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).* (\d{2}):(\d{2}):(\d{2}).*"}/','$2',$keywords[$x]);
    			  			//$yyyy=preg_replace('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).* (\d{2}):(\d{2}):(\d{2}).*"}/','$3',$keywords[$x]);
    			  			//$hh=preg_replace('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).*(\d{2}):(\d{2}):(\d{2}).*"}/','$4',$keywords[$x]);
    			  			//$min=preg_replace('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).*(\d{2}):(\d{2}):(\d{2}).*"}/','$5',$keywords[$x]);
    			  			//$ss=preg_replace('/"dateTime": "(\d{2})\.(\d{2})\.(\d{4}).*(\d{2}):(\d{2}):(\d{2}).*"}/','$6',$keywords[$x]);
    			  			
    			  			echo "<br>dateTime : Jour : " . $matches[1] . " Mois :" . $matches[2] . " Annee :" . $matches[3] . " " . $matches[4] . ":" . $matches[5] . " " . $matches[6] . "<br>";
                            $datetime=$matches[3]."-".$matches[2]."-".$matches[1]." ".$matches[4].":".$matches[5].":".$matches[6];
    						}
    						$x++;
    					}
    					print_r($keywords);
    					//echo "<h1><br> Mapname found<br></h1>";
    					$x=0;
    					echo "<table><tr><td>Team 1</td><td>Vehicule</td><td>Team 2</td><td>Vehicule</td></tr>";
    					while($x<15){
    						echo "<tr><td>".$name[$team1[$x]];
    						if ($clanAbbrev[$team1[$x]]!== ''){
    							echo "[".$clanAbbrev[$team1[$x]]."]";
    						}
    						echo "</td><td>".$vehicleType[$team1[$x]]."</td>".
    						"<td>".$name[$team2[$x]];
    						if ($clanAbbrev[$team2[$x]]!== ''){
    							echo "[".$clanAbbrev[$team2[$x]]."]";
 							}
    					echo "</td><td>".$vehicleType[$team2[$x]]."</td></tr>";	
    					$x++;
    					}
    					echo "</table>";
    					echo uniqid("", true);
    				}

   				//echo "<br><br> line : ".$line."<br><br>";
      		}
      		$query = $db->getQuery(true);
      		$battleuniq=uniqid("", true);
  			$query="INSERT `#__wotclan_battle` (`id`,`uniqid`, `team1`,`tanks1`,`team2`,`tanks2`,`datebattle`)
    							VALUES (NULL,'".$battleuniq."','".$steam1."','".$sttankt1."','".$steam2."','".$sttankt2."','".$datetime."');";
	    	#$db->setQuery($query);
            #$db->query();
            if ($_POST['notshare'] || $_GET['notshare'] == 1) {
                echo "<h1>to be deleted : </h1>" . JPATH_ROOT.DS. "media" . DS . "wotclan" . DS . "replays" . DS . $repuniq . DS . $filename ;
                unlink(JPATH_ROOT.DS. "media" . DS . "wotclan" . DS . "replays" . DS . $repuniq . DS . $filename );
            } else {
                $query = $db->getQuery(true);
                $replayuniq=uniqid("", true);
                $path_parts = pathinfo($_FILES["file_upload"]["name"]);
                $query="INSERT `#__wotclan_replays` (`id`,`uniqid`, `file`, `uid`, `battle`, `datebattle`)
            
    							VALUES (NULL,'".$replayuniq."','".$path_parts['filename'].".wotreplay','".$usr_id."','".$battleuniq."','".$datetime."');";
  	            $db->setQuery($query);
                $db->query();
                echo "<h1>".$query."</h1>";
            }
   		
            }
                    unlink($dest);
  					$zip->close();
  					echo 'woot!';
          } else {
  					echo 'doh!';
          }
    
   	 			//Redirect to a page of your choice
    			echo "all is ok";
    
    				} else {
      		//Redirect and throw an error message
      		echo "error message";
   			}
		 } else {
   		//Redirect and notify user file is not right extension
   		echo "no right extension";
		 }
    } else {
    		$greeting = "Vous n'avez pas acces a cette section!";
        $this->assignRef( 'greeting', $greeting );
 
        parent::display($tpl);
    		
    }
	}
}




